package com.winit.openapi.util;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.SPIException;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;

/**
 * 
 * FastJson工具类
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * sheng.huang 	1.0  		2016年5月13日 	Created
 *
 * </pre>
 * @since 1.
 */
public class FastJSONUtils {
    private static Logger logger = LoggerFactory.getLogger(FastJSONUtils.class);
    /**
     * JSON转java对象
     * 
     * @param obj
     * @param type
     * @return
     */
    public static <E> E toJavaObject(Object obj, Class<E> type) {
        if (obj == null) return null;
        if (obj instanceof JSONObject) {
            JSONObject json = JSONObject.parseObject(obj.toString());
            try {
                return JSONObject.toJavaObject(json, type);
            } catch (SPIException e) {
                throw new ApiException(ErrorCode.JSON_TO_JAVAOBJECT_EROOR, "data");
            } catch (Exception e1) {
                logger.info(e1.getMessage());
            }
        } else {
            throw new ApiException(ErrorCode.JSON_FORMAT_ERROR, "data");
        }
        return null;
    }
    
    /**
     * JSON List解析方法
     * @param obj json对象
     * @param type class文件
     * @param splat 解析的节点
     * @return
     */
    public static <E> List<E> getObjectList(Object obj, Class<E> type, String splat) {
        JSONObject jsonObj = JSON.parseObject(obj.toString());
        JSONArray result = jsonObj.getJSONArray(splat);
        List<E> links = JSON.parseArray(result.toJSONString(), type);
        return links;
    }
}
